package iammry.com.utils;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;


/**
 * 
 * @author kim
   @time 2016-3-7上午11:36:00
   @des 将错误信息保存到本地
   @version  1.0
 *
 */
public class CrashHandler implements UncaughtExceptionHandler {
	private static CrashHandler crashHandler;

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		// TODO Auto-generated method stub
		if (crashHandler != null) {
			try {
				// 将crash log写入文件
				FileOutputStream fileOutputStream = new FileOutputStream(
						"/mnt/sdcard/zz_crash_log.txt", true);
				PrintStream printStream = new PrintStream(fileOutputStream);
				ex.printStackTrace(printStream);
				printStream.flush();
				printStream.close();
				fileOutputStream.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// 设置默认处理器
	public void init() {
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	private CrashHandler() {
	}

	// 单例
	public static synchronized CrashHandler instance() {
		if (crashHandler == null) {

			crashHandler = new CrashHandler();

		}
		return crashHandler;
	}
}
